<?php

namespace app\agent\model;

use app\model\AgentWithdraw;
use app\model\AgentWithdrawConfig;
use think\facade\Db;

/**
 * 代理商提现.
 */
class Withdraw
{
    private $table = 'agent_withdraw';

    /**
     * 列表.
     */
    public function getList($params)
    {
        $where = [];
        $where[] = ['agent_id', '=', $params['agent_id']];
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }
        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        $list = Db::name($this->table)
            ->where($where)
            ->order('id desc')
            ->paginate($paginate)
            ->toArray();
        $agent = Db::name('agent')
            ->field('balance, profit_balance,is_relation')
            ->where('id', $params['agent_id'])
            ->find();
        $list['balance'] = $agent['balance'] ?? 0;
        $list['profit_balance'] = $agent['profit_balance'] ?? 0;
        $list['is_relation'] = $agent['is_relation'] ?? 0;

        return success('操作成功', $list);
    }

    /**
     * 添加.
     */
    public function create($agentId, $params)
    {

        $amount = yuan2fen($params['amount']);

        // step 提现设置
        $withdrawConfig = AgentWithdrawConfig::where('agent_id', 0)->find();


        if ($withdrawConfig) {

            $todayCount = AgentWithdraw::where('agent_id', $agentId)->where('created_at', '>=', date('Y-m-d') . ' 00:00:00')->count();
            if ($todayCount >= $withdrawConfig->day_max_freq) {
                return fail('每天限制提现 ' . $withdrawConfig->day_max_freq . ' 次');
            }

            $minAmount = yuan2fen($withdrawConfig->min_amount);
            if ($amount < $minAmount) {
                return fail('提现金额不能低于：' . $withdrawConfig->min_amount . ' 元');
            }

            $charge = intval(strval($amount * $withdrawConfig->rate / 100)); // 手续费
            $realPrice = $amount - $charge;
            $autoApproveMax = yuan2fen($withdrawConfig->auto_aprove_max);
        } else {
            $charge = 0;
            $realPrice = $amount;
            $autoApproveMax = -1;
        }
        if ($withdrawConfig && $amount <= $autoApproveMax) {
            $status = 2;
            $remark = '申请提现且自动通过审核 ';
        } else {
            $status = 1;
            $remark = '申请提现 ';
        }

        $fields = [
            'alipay', 'mobile', 'wechat', 'bank_card_no',
            'bank_username', 'bank_name', 'user_remark',
        ];
        foreach ($fields as $field) {
            if (!isset($params[$field])) {
                $params[$field] = '';
            }
        }

        Db::startTrans();
        try {
            $profitBalance = Db::name('agent')
                ->where('id', $agentId)
                ->lock(true)
                ->value('profit_balance');
            if ($amount > $profitBalance) {
                Db::rollback();
                return fail('账户余额不足。当前佣金余额：' . fen2yuan($profitBalance) . ' 元');
            }
            $agentWithdraw = AgentWithdraw::create([
                'agent_id' => $agentId,
                'amount' => $amount,
                'charge' => $charge,
                'real_price' => $realPrice,
                'type' => $params['type'],
                'alipay' => $params['alipay'],
                'mobile' => $params['mobile'],
                'wechat' => $params['wechat'],
                'bank_card_no' => $params['bank_card_no'],
                'bank_username' => $params['bank_username'],
                'bank_name' => $params['bank_name'],
                'user_remark' => $params['user_remark'],
                'status' => $status,
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('申请失败：' . $e->getMessage() . $e->getLine());
        }

        return success('申请成功', [
            'id' => intval($agentWithdraw->id),
        ]);
    }

    /**
     * 撤销
     */
    public function cancel($params)
    {
        if (empty($params['id'])) {
            return fail('参数有误');
        }
        $info = Db::name($this->table)
            ->where('id', $params['id'])
            ->where('agent_id', $params['agent_id'])
            ->find();
        if (empty($info)) {
            return success('提现申请不存在');
        }

        if (1 != $info['status']) {
            return fail('待审核的提现申请才能撤销');
        }

        Db::startTrans();
        try {
            $res = Db::name($this->table)
                ->where('id', $info['id'])
                ->where('status', 1)
                ->update([
                    'status' => 4,
                ]);
            if (!$res) {
                Db::rollback();
                return fail('待审核的提现申请才能撤销。');
            }
            $profitBalance = Db::name('agent')
                ->where('id', $info['agent_id'])
                ->lock(true)
                ->value('profit_balance');

            Db::name('agent')
                ->where('id', $info['agent_id'])
                ->inc('profit_balance', $info['amount'])
                ->update([
                    'balance_last_updated_at' => date('Y-m-d H:i:s'),
                ]);
            Db::name('agent_balance_log')
                ->insert([
                    'agent_id' => $info['agent_id'],
                    'type' => BALANCE_WITHDRAW_CANCEL,
                    'amount' => $info['amount'],
                    'old_balance' => $profitBalance,
                    'new_balance' => $profitBalance + $info['amount'],
                    'remark' => '撤销提现申请 ' . fen2yuan($info['amount']) . ' 元',
                    'quote_id' => $info['id'],
                ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('撤销: ' . $e->getMessage());
        }

        return success('撤销成功');
    }
}
